import router from './router'
import { asyncRoutes } from '@/router'
import store from './store'

// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

// // 白名单，不需要的登陆就可以访问
const whiteList = ['/login', '/404'] // no redirect whitelist

// 全局前置守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start()

  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const userInfo = store.state.user.userInfo
      if (Object.keys(userInfo).length <= 0) {
        // 可以获取到用户有哪些权限
        const { roles: { menus }} = await store.dispatch('user/getUserInfo')
        // 1.先筛选出符合条件的路由规则
        // asyncRoutes 先筛选
        // 根据asyncRoutes 和menus 先筛选
        const otherRoutes = asyncRoutes.filter(item => {
          return menus.includes(item.children[0].name)
        })
        store.commit('permission/setRoutes', [...otherRoutes, { path: '*', redirect: '/404', hidden: true }])
        // 2.动态添加符合条件的路由规则
        // addRoutes 是异步的
        // 此处负责页面跳转，存在vuex中的负责动态 渲染侧边栏
        router.addRoutes([...otherRoutes, { path: '*', redirect: '/404', hidden: true }])
        // 作用：保证addRoutes这个异步操作执行完毕
        next({
          // path: to.path,
          // query: to.query,
          ...to,
          // 替换历史记录中的地址
          replace: true
        })
        return
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      NProgress.done()
      next({ path: '/login' })
    }
  }
})

// 全局后置守卫
router.afterEach((to, from) => {
  NProgress.done()
})
